<template>
  <div>
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="所属机房:" prop="computer">
        <el-select
          v-model="form.computer"
          placeholder="请选择"
          @change="getvpns"
        >
          <el-option
            v-for="item in computers"
            :key="item.id"
            :label="item.tcrname"
            :value="item.tcrcode"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="VPN:" prop="vpn">
        <el-select
          v-model="form.vpn"
          filterable
          placeholder="请选择"
          multiple
          collapse-tags
          clearable
          @change="changeSelect"
          @visible-change="handleSelectVisibleChange"
        >
          <div class="select-header" v-if="vpns.length > 0">
            <span class="checkAll">全选</span>
            <el-checkbox v-model="checked" @change="selectAll" />
          </div>
          <el-option
            v-for="item in vpns"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="时间段:" prop="time">
        <el-select v-model="form.time" placeholder="请选择">
          <el-option
            v-for="item in times"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="refresh">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="lineChart">
      <div v-if="lineChartData.length == 0">
        <div class="equty">
          <span>请依次选择查询条件,查询数据</span>
          <!-- <div>暂无数据</div> -->
        </div>
      </div>
      <line-chart v-else :chartData="lineChartData" />
    </div>
  </div>
</template>

<script>
import LineChart from "@/views/dashboard/LineChart";
import { getLines, getComputers, getVpns } from "@/api/ipkeeplive/audit";
import moment from "moment";
const lineChartData = {
  newVisitis: {
    expectedData: [100, 120, 161, 134, 105, 160, 165],
    actualData: [120, 82, 91, 154, 162, 140, 145],
    xdata: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
  },
  messages: {
    expectedData: [200, 192, 120, 144, 160, 130, 140],
    actualData: [180, 160, 151, 106, 145, 150, 130],
    xdata: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
  },
  purchases: {
    expectedData: [80, 100, 121, 104, 105, 90, 100],
    actualData: [120, 90, 100, 138, 142, 130, 130],
    xdata: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
  },
  shoppings: {
    expectedData: [130, 140, 141, 142, 145, 150, 160],
    actualData: [120, 82, 91, 154, 162, 140, 130],
    xdata: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
  },
};
function filin(arr) {
  let list = [];
  // arr.filter((item) => !list.includes(item.value) && list.push(item.value))
  return arr.filter(
    (item) => !list.includes(item.value) && list.push(item.value)
  );
}
export default {
  name: "Index",
  components: {
    LineChart,
  },
  data() {
    return {
      lineChartData: [],
      timeId: null,
      form: {
        computer: "",
        vpn: [],
        time: "",
      },
      checked: false,
      computers: [],
      vpns: [],
      times: [
        {
          value: 30,
          label: "半小时内",
        },
        {
          value: 60,
          label: "1小时内",
        },
        {
          value: 120,
          label: "2小时内",
        },
        {
          value: 180,
          label: "3小时内",
        },
        {
          value: 360,
          label: "6小时内",
        },
        {
          value: 720,
          label: "12小时内",
        },
        {
          value: 1440,
          label: "24小时内",
        },
      ],
      devoptions: [],
    };
  },
  created() {
    this.init();
    this.getcomputers();
  },
  methods: {
    async getcomputers() {
      const res = await getComputers();
      if (res.code === 200) {
        this.computers = res.rows.filter((i) => i.tcrcode && i.tcrname);
      } else {
        this.$message.error(res.msg);
      }
    },
    async getvpns(tcr = "") {
      if (!tcr) {
        return false;
      }
      const curpathname = window.location.pathname;
      const deviceType = curpathname.includes("edgevpn") ? 1 : 0;
      let params = {
        tcrCode: tcr,
        deviceType,
      };
      const res = await getVpns(params);
      if (res.code === 200) {
        res.rows = res.rows.filter((i) => i);
        // const a = res.rows.map(i => ({
        //     label: i.netIp,
        //     value: i.netIp,
        //     id: i.deviceId
        // }))
        const a = res.rows.map((i, index) => ({
          label: i,
          value: i,
          id: index,
        }));
        this.vpns = filin(a);
        this.form.vpn.splice(0);
        this.checked = false;
      } else {
        this.$message.error(res.msg);
      }
    },
    handleSelectVisibleChange(v) {
      if (v && this.form.computer == "") {
        this.$message.error("请先选择机房信息，才能选择vpn信息");
      }
    },
    init() {
      this.getlines();
    },
    getlines() {
      if (this.timeId) {
        clearInterval(this.timeId);
      }
      const { computer: tcr, vpn: netIpList, time: timeSlot } = this.form;
      if (netIpList.length == 0 || !timeSlot) {
        this.lineChartData.splice(0);
        return false;
      }
      const fn = (num) => (num % 5 === 0 ? num : num - (num % 5));
      const endTime = moment().format("YYYY-MM-DD HH:mm:ss");
      const startTime = moment(endTime)
        .subtract(timeSlot, "minutes")
        .format("YYYY-MM-DD HH:mm:ss");
      const n = endTime.substr(13, 4);
      const b = moment().format("mm");
      const charttime = endTime.replace(n, `:${fn(b)}:`);
      const curpathname = window.location.pathname;
      let params = {
        netIpList: netIpList.join(","),
        startTime,
        endTime,
        tcrCode: tcr,
        // timeSlot,
        boxType: curpathname.includes("edgevpn") ? 1 : 0,
      };
      getLines(params).then((res) => {
        //console.log(res);
        // const arr = [1, 2, 3, 4, 5, 6, 7]
        // this.lineChartData.xdata = arr.map((i) => {
        //     return moment().subtract(i, 'minutes').format('HH:mm')
        // }).reverse()
        let num = this.form.time / 5;
        let nums = [];
        for (let index = 0; index < num; index++) {
          nums.push(index * 5);
        }
        let endt = nums
          .map((i) => {
            return moment(charttime).subtract(i, "minutes").format("HH:mm");
          })
          .reverse();
        let endtstr = nums
          .map((i) => {
            return moment(charttime)
              .subtract(i, "minutes")
              .format("YYYY-MM-DD HH:mm:00");
          })
          .reverse();
        //console.log(endtstr);
        const monitorData = endtstr.map((i) => ({
          // timePiont:i,
          timePiont: i.slice(11),
          timePiontCount: 0,
        }));
        setTimeout(() => {
          if (res.code == 200) {
            let list = res.rows;
            for (let index = 0; index < list.length; index++) {
              const it = list[index].monitorData;
              let nums = [];
              let times = [];
              list[index].nums = nums;
              list[index].times = times;
              for (let j = 0; j < endtstr.length; j++) {
                const i = endtstr[j];
                if (it.findIndex((ta) => i == ta.onlineDatetime) != -1) {
                  nums.push(it.find((ta) => i == ta.onlineDatetime).onlineNum);
                  times.push(
                    it
                      .find((ta) => i == ta.onlineDatetime)
                      .onlineDatetime.slice(11, 16)
                  );
                } else {
                  nums.push(0);
                  times.push(endt[j]);
                }
              }
            }
            this.lineChartData = res.rows;
          }
        }, 500);
        this.timeId = setInterval(() => {
          this.getlines();
        }, 5 * 60 * 1000);
      });
    },
    refresh() {
      const { computer: tcr, vpn: netIpList, time: timeSlot } = this.form;
      if (tcr == "") {
        this.$message.error("请先选择机房信息！");
        return false;
      } else if (netIpList.length == 0) {
        this.$message.error("请先选择vpn信息！");
        // this.$notify({
        //   customClass: "tippp",
        //   position: "top-left",
        //   duration: 0,
        //   type: "warning",
        //   message: "请先选择vpn信息",
        //   offset: 170,
        // });
        return false;
      } else if (timeSlot == "") {
        this.$message.error("请先选择时间段！");
        return false;
      }
      this.getlines();
    },
    resetForm() {
      this.$refs["form"].resetFields();
      this.vpns.splice(0);
      this.getlines();
    },
    selectAll() {
      this.form.vpn = [];
      // this.checked = !this.checked;
      if (this.checked) {
        this.vpns.map((item) => {
          this.form.vpn.push(item.value);
        });
      } else {
        this.form.vpn = [];
      }
    },
    changeSelect(val) {
      if (val.length === this.vpns.length) {
        this.checked = true;
      } else {
        this.checked = false;
      }
    },
  },
  beforeDestroy() {
    clearInterval(this.timeId);
  },
};
</script>

<style scoped lang="scss">
.queryform {
  ::v-deep .el-form {
    display: flex;
    flex-wrap: wrap;

    .el-form-item {
      max-width: 25%;
      flex-grow: 1;
      flex-shrink: 1;
      flex-basis: 25%;
    }

    .el-form-item:nth-child(2) {
      max-width: 26%;
      flex-grow: 1;
      flex-shrink: 1;
      flex-basis: 26%;
    }

    .el-form-item:nth-child(4) {
      max-width: 24%;
      flex-grow: 1;
      flex-shrink: 1;
      flex-basis: 24%;
    }

    // .el-form-item:nth-child(7) {
    //   max-width: 100%;
    //   flex-basis: 100%;
    //   display: flex;
    //   justify-content: end;
    // }
  }
}
.select-header {
  display: flex;
  width: 100%;
  // justify-content: space-between;
  font-size: 14px;
  padding: 0 20px;
  position: relative;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #606266;
  height: 34px;
  line-height: 34px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  cursor: pointer;
  .checkAll {
    margin-right: 5px;
  }
}
.lineChart {
  border: 1px solid #e5e5e5;
  border-radius: 3px;
  padding: 17px 16px 7px 16px;
  /* width: 1158px; */
  width: 1200px;
  position: relative;

  .equty {
    display: flex;
    width: 1160px;
    height: 390px;
    color: #606266;
    transform: translateY(-10%);
    justify-content: center;
    align-items: center;
  }
}
</style>
